﻿//
// Created by sail on 19-6-13.
//

#include "Messenger.h"
#include "common/ControlCommands.h"
#include <iostream>

Messenger::Messenger():
    QObject(nullptr),
    _tcpSocket(std::make_shared<QTcpSocket>(this))
{
    connect(_tcpSocket.get(),&QTcpSocket::connected,[&](){
        qDebug()<<"Connect Server";
        Q_EMIT onConnectServer();
    });
    connect(_tcpSocket.get(),&QTcpSocket::disconnected,[&](){
        qDebug()<<"Break Server";
        Q_EMIT onDisconnectServer();
    });
//    connect(_tcpSocket.get(),&QTcpSocket::readyRead, [&](){
//        QByteArray originalM = _tcpSocket->readAll();
//        dataTransform d;
//        for(int i = 0;i < 2;++i)
//            d.data[i] = originalM[i];
//        _FPGAData = 0;
//        for(int i = 0;i < 16;++i)
//            _FPGAData |= (d.num & (1 << i));
//        qDebug()<<"from serve:"<<_FPGAData;
//    });
}

Messenger::~Messenger()
{

}

void Messenger::ConnectServer(QString ip,quint16 port)
{
    _tcpSocket->connectToHost(ip, port);
}

void Messenger::DisconnectServer()
{
    if(_tcpSocket->isOpen())
    {
        _tcpSocket->close();
    }
}

void Messenger::write(const QByteArray& a) {
//    qDebug()<<a;
    _tcpSocket->write(a);
}

bool Messenger::isOpen(){
    return _tcpSocket->isOpen();
}

int Messenger::ByteToInt(const QByteArray& originalM){
    dataTransform d;
    int res = 0;
    for(int i = 0;i < 2;++i)
        d.data[i] = originalM[i];
    for(int i = 0;i < 16;++i)
        res |= (d.num & (1 << i));
    return res;
}

void Messenger::writeAndPromise(const QByteArray& data, int target){
//    qDebug()<<data;
    while(_FPGAData != target){
        _tcpSocket->write(data);
        _tcpSocket->waitForBytesWritten(100);
        _tcpSocket->write("READ");
        _tcpSocket->waitForReadyRead(100);
        _FPGAData = ByteToInt(_tcpSocket->readAll());
//        qDebug()<<"from serve:"<<ByteToInt(_tcpSocket->readAll());
    }
//    qDebug()<<"FPGAData:"<<_FPGAData;
}

